package scene_info_dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type Scene struct {
	RoleId      int64                                 `gorm:"column:role_id"`
	SceneInfo   datatypes.JSONType[map[int32][]int32] `gorm:"column:scene_info"`
	BoxInfo     datatypes.JSONType[map[int32][]int32] `gorm:"column:box_info"`
	CreateTime  int64                                 `gorm:"column:create_time"`
	UpgradeTime int64                                 `gorm:"column:upgrade_time"`
}

func (Scene) TableName() string {
	return "scene_info"
}

var (
	all_scene_field = zutils.GetGormFields(Scene{})
)

func GetSceneByRoleId(RoleId int64, fields ...[]string) *Scene {
	var selectFields []string

	if len(fields) > 0 {
		selectFields = fields[0]
	} else {
		selectFields = all_scene_field
	}

	db := mysql.GetServerDBConnection()
	var scene Scene
	if err := db.Select(selectFields).Where("role_id=?", RoleId).First(&scene).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetSceneByKey ERR!!! RoleId: %s, err: %v", RoleId, err)
		}
		return nil
	}
	return &scene
}

func UpdateSceneByRoleId(RoleId int64, changeField *map[string]any) {
	db := mysql.GetServerDBConnection()
	if err := db.Model(Scene{}).Where("role_id=?", RoleId).Updates(changeField).Error; err != nil {
		zlog.Errorf("UpdateSceneByKey %s data failed: %v", RoleId, err)
	}
}

func CreateSceneInfo(roleId int64, sceneInfo *map[int32][]int32, createTime int64) {
	scene := &Scene{
		RoleId:      roleId,
		SceneInfo:   datatypes.NewJSONType(*sceneInfo),
		BoxInfo:     datatypes.NewJSONType(make(map[int32][]int32)),
		CreateTime:  createTime,
		UpgradeTime: createTime,
	}

	db := mysql.GetServerDBConnection()
	if err := db.Create(scene).Error; err != nil {
		zlog.Errorf("CreateSceneInfo %v data failed: %v", scene, err)
	}
}
